package com.rt.cms.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @classname: 短信发送
 * @author：
 * @time： 2017/5/26
 */
public class SendMessageUtil {

    public static String postUrl(String intputString, String url, String tel) {

        // 短信接口调试前，暂时屏蔽
//        if(true){
//            return "";
//        }

        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();


        String appid = "cms";
        String datetime = String.valueOf(new Date().getTime());

        StringBuffer buffer = new StringBuffer("appid=");
        buffer.append(appid);
        buffer.append("&shouji=");
        buffer.append(tel);
        buffer.append("&shijian=");
        buffer.append(datetime);

        String token = MD5.GetMD5Code(buffer.toString());

        params.add(new BasicNameValuePair("shouji", tel));
        params.add(new BasicNameValuePair("token", token));
        params.add(new BasicNameValuePair("appid", appid));
        params.add(new BasicNameValuePair("shijian", datetime));
        params.add(new BasicNameValuePair("MSG", intputString));

        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 设置参数给Post
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (!response.getStatusLine().getReasonPhrase().equals("OK")) {
                //return "发送交易失败!";
                return null;
            }
            //读取返回信息
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    entity.getContent(), "UTF-8"));
            StringBuffer buffer1 = new StringBuffer();
            String line = reader.readLine();

            while (line != null) {
                buffer1.append(line);
                line = reader.readLine();
            }
            return buffer1.toString();

        } catch (Exception e) {

        }
        return null;
    }

}
